//
//  CPPercentDrivenInteractiveTransition.m
//  zent
//
//  Created by Morplcp on 2018/11/2.
//  Copyright © 2018 zentcm. All rights reserved.
//

#import "CPPercentDrivenInteractiveTransition.h"
#import "CPFrameworkMacro.h"

@interface CPPercentDrivenInteractiveTransition ()

@property (nonatomic, assign) CGFloat start_x;

@end

@implementation CPPercentDrivenInteractiveTransition

- (instancetype)initWithVc:(UIViewController *)vc
{
    self = [super init];
    if (self)
    {
        _vc = vc;
        _start_x = 0;
        UIScreenEdgePanGestureRecognizer *panGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHander:)];
        panGesture.edges = UIRectEdgeLeft;
        [vc.view addGestureRecognizer:panGesture];
    }
    return self;
}

- (void)panGestureHander:(UIScreenEdgePanGestureRecognizer *)gesture
{
    switch (gesture.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            _isInteracting = YES;
            _start_x = [gesture locationInView:_vc.view].x;
            [_vc dismissViewControllerAnimated:YES completion:nil];
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            CGFloat fraction;
            CGFloat point_x = CP_SCREEN_WIDTH + [gesture locationInView:_vc.view].x;
            fraction = (point_x / CP_SCREEN_WIDTH);
            fraction = fmin(fmaxf(fraction, 0.0), 1.0);
         
            _shouldComplete = fraction > 0.5;
            [self updateInteractiveTransition:fraction];
            break;
        }
        case UIGestureRecognizerStateEnded:
        {
            _isInteracting = NO;
            if (!_shouldComplete || gesture.state == UIGestureRecognizerStateCancelled)
            {
                [self cancelInteractiveTransition];
            }
            else
            {
                [self finishInteractiveTransition];
            }
            break;
        }
        default:
            break;
    }
}

@end
